package demo;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;
class Account {
    private String name;
    private int asset;
    private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    public Account(String name, int asset) {
        this.name = name;
        this.asset = asset;
    }
    public void save(int asset) {
        this.readWriteLock.writeLock().lock();
        try {
            this.asset += asset;
            TimeUnit.SECONDS.sleep(1);
            System.out.println("【" + Thread.currentThread().getName() + "】修改银行资产，当前的资产为：" + (this.asset / 100.0));
        } catch (Exception e) {
        } finally {
            this.readWriteLock.writeLock().unlock();
        }
    }
    public String toString() {
        this.readWriteLock.readLock().lock();
        try {
            TimeUnit.MILLISECONDS.sleep(100);
            return "【" + Thread.currentThread().getName() + "】账户名称：" + this.name + "，账户余额：" + (this.asset / 100.0);
        } catch (Exception e) {
            return null;
        } finally {
            this.readWriteLock.readLock().unlock();
        }
    }
}
public class YootkDemoP252 {
    public static void main(String[] args) throws Exception {
        Account account = new Account("李兴华", 0);
        int money[] = new int[] {110, 230, 10_000};
        for (int x = 0; x < 10; x++) {
            if (x < 2) {
                new Thread(() -> {
                    for (int y = 0; y < money.length; y++) {
                        account.save(money[y]);
                    }
                }, "存款者 - " + x).start();
            } else {
                new Thread(() -> {
                    while (true) {
                        System.out.println(account);
                    }
                }, "查询者 - " + x).start();
            }
        }
    }
}
